package cn.dam.api.service.impl;



import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import cn.dam.api.entity.UserEntity;
import cn.dam.api.service.MemberService;
import cn.dam.api.service.dao.UserDao;
import cn.dam.base.BaseApiService;
import cn.dam.base.BaseRedisService;
import cn.dam.base.ResponseBase;
import cn.dam.constants.Constants;
import cn.dam.mq.RegisterMailboxProducer;
import cn.dam.utils.MD5Util;
import cn.dam.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
@RestController
@Slf4j
public class MemberServiceImpl extends BaseApiService implements MemberService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private RegisterMailboxProducer registerMailboxProducer;
	@Value("${messages.queue}")
	private String MESSAGEQUEUE;
	@Autowired
	private BaseRedisService baseRedisService;

	@Override
	public ResponseBase findUserById(Long userId) {
		UserEntity user = userDao.findByID(userId);
		return user==null?setResultError("未找到用户信息"):setResultSuccess(user);
	}

	@Override
	public ResponseBase regUser(@RequestBody UserEntity userEntity) {
		// 参数验证
		String password=userEntity.getPassword();
		if(StringUtils.isEmpty(password)) {
			 return setResultError("密码不能为空");
		}
		userEntity.setPassword(MD5Util.MD5(password));
		Integer result = userDao.insertUser(userEntity);
		if(result<=0) {
			return setResultError("注册用户信息失败");
		}
		//采用异步方式发送短信
		String email=userEntity.getEmail();
		String json=emailJson(email);
		log.info("#########会员服务推送消息到消息服务平台##############json：{}",json);
		sendMsg(json);
		return setResultSuccess("注册成功");
	}
	private String emailJson(String email) {
		JSONObject rootJson = new JSONObject();
		JSONObject header = new JSONObject();
		header.put("interfaceType", Constants.MSG_EMAIL);
		JSONObject content= new JSONObject();
		content.put("email", email);
		rootJson.put("header", header);
		rootJson.put("content", content);
		return rootJson.toJSONString();	
	}
	
	private void sendMsg(String json) {
		ActiveMQQueue activeMQQueue = new ActiveMQQueue(MESSAGEQUEUE);
		registerMailboxProducer.sendMsg(activeMQQueue, json);
	}

	@Override
	public ResponseBase login(@RequestBody UserEntity userEntity) {
		//1、验证参数
		String  username=userEntity.getUsername();
		if(StringUtils.isEmpty(username)) {
			return setResultError("用户名称不能为空！");
		}
		String password=userEntity.getPassword();
		if(StringUtils.isEmpty(password)) {
			return setResultError("密码不能为空！");
		}
		String newPassWord =MD5Util.MD5(password);
		UserEntity user=userDao.login(username, newPassWord);
		//2、数据库查找账号密码是否正确
		if(null==user) {
			return setResultError("账号或者密码不正确");
		}
		//3、如果账号密码正确，对应生成token
		String memberToken = TokenUtils.getMemberToken();
		//4、存放在redis中之后,key为token value为userId
		Integer userId=user.getId();
		log.info("#######用户信息token存放在Redis中...key为：{},value:{}",memberToken,userId);
		baseRedisService.setString(memberToken, userId+"", Constants.TOKEN_MEMBER_TIME);
		//5、直接返回token
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("memberToken", memberToken);
		return setResultSuccess(jsonObject);
	}

	@Override
	public ResponseBase findByTokenUser(@RequestParam(name="token") String token) {
		// 1、验证参数
		if(StringUtils.isBlank(token)) {
			return setResultError("token不能为空！");
		}
		//2、从redis中使用token查找对应userId
		String userId=(String)baseRedisService.getString(token);
		if(StringUtils.isEmpty(userId)) {
			return setResultError("token无效或者已经过期！");
			
		}
		//3、使用userId数据库查询用户信息返回给客户端
		Long uid=Long.parseLong(userId);
		UserEntity userEntity = userDao.findByID(uid);
		if(userEntity==null) {
			return setResultError("未查找到该用户的信息");
		}
		return setResultSuccess((userEntity));
	
	}


}
